﻿using Gateway.Common.Enums;
using Gateway.Common.Extensions;
using Gateway.Domain.EFCore.Configuration;
using Gateway.Domain.Entities;
using Gateway.Domain.SeedModule;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Gateway.Domain.Configuration;

public class RoleMenuConfiguration : EntityConfiguration<RoleMenu>
{
    public override void Configure(EntityTypeBuilder<RoleMenu> builder)
    {
        builder.ToTable(t => t.HasComment("角色菜单配置表"));
        builder.Property(x => x.RoleId).IsRequired().HasMaxLength(36).HasComment("角色标识");
        builder.Property(x => x.MenuId).IsRequired().HasMaxLength(36).HasComment("菜单标识");
        builder.HasOne(x => x.Role).WithMany(x => x.RoleMenus)
            .HasForeignKey(x => x.RoleId)
            .OnDelete(DeleteBehavior.Cascade);
        SetSeed(builder);
        base.Configure(builder);
    }

    private void SetSeed(EntityTypeBuilder<RoleMenu> builder)
    {
        var dir = AppDomain.CurrentDomain.BaseDirectory;

        string path = Path.Combine(dir,"appsettings", "Seed", "rolemenu.json");
        var data = path.ParseJsonFile<List<RoleMenuSeedModel>>();
        List<RoleMenu> roleMenus = new List<RoleMenu>();
        foreach (var item in data)
        {
            var roleMenu = new RoleMenu(item.RoleId, item.MenuId);
            roleMenu.SetDefaultId(item.RoleMenuId);
            roleMenus.Add(roleMenu);
        }

        builder.HasData(roleMenus);
    }
}